package logger

import (
	"fmt"
	"github.com/DiracLee/dires-go/utils"
	"io"
	"log"
	"time"
)

type WriterConfig interface {
	Build() io.Writer
}

type FileWriterConfig struct {
	DirPath              string
	FileName             string
	FileExt              string
	FileSuffixTimeFormat string
}

func NewFileWriterConfig(options ...Option) *FileWriterConfig {
	cfg := &FileWriterConfig{
		DirPath:              "logs",
		FileName:             "godis",
		FileExt:              "log",
		FileSuffixTimeFormat: "2006-01-02",
	}
	for _, option := range options {
		option.Apply(cfg)
	}
	return cfg
}

func (cfg *FileWriterConfig) Build() io.Writer {
	var err error
	dir := cfg.DirPath
	fileName := fmt.Sprintf("%s-%s.%s",
		cfg.FileName,
		time.Now().Format(cfg.FileSuffixTimeFormat),
		cfg.FileExt)

	logFile, err := utils.ForceOpen(fileName, dir)
	if err != nil {
		log.Fatalf("logging.Setup err: %s", err)
	}
	return logFile
}

type Option interface {
	Apply(*FileWriterConfig)
}

type OptionFunc func(cfg *FileWriterConfig)

func (f OptionFunc) Apply(cfg *FileWriterConfig) {
	f(cfg)
}

func WithDirPath(path string) Option {
	return OptionFunc(func(cfg *FileWriterConfig) {
		cfg.DirPath = path
	})
}

func WithFileName(name string) Option {
	return OptionFunc(func(cfg *FileWriterConfig) {
		cfg.FileName = name
	})
}

func WithFileExt(ext string) Option {
	return OptionFunc(func(cfg *FileWriterConfig) {
		cfg.FileExt = ext
	})
}

func WithFileSuffixTimeFormat(timeFormat string) Option {
	return OptionFunc(func(cfg *FileWriterConfig) {
		cfg.FileSuffixTimeFormat = timeFormat
	})
}
